const Koa = require('koa');
const KoaRouter = require('koa-router');
const KoaStatic = require('koa-static');
const axios = require('axios');
const querystring = require('querystring');
const jwt = require('jsonwebtoken');
const jwtAuth = require('koa-jwt');

const app = new Koa();
const router = new KoaRouter();

const accessTokens = {};
const secret = '1237912u392h193h2193';

const config = {
    client_id: '35671930f06fcbd1ceb7',
    client_secret: '42dd7105abae034bcfca12ebfc0f61db4e2ff79b',
};

router.get('/github/login', async (ctx) => {
    const path = `https://github.com/login/oauth/authorize?client_id=${config.client_id}`;
    ctx.redirect(path);
});

router.get('/github/callback', async (ctx) => {
    // 接收 code
    const { code } = ctx.query;
    // 获取 token
    const data = {
        ...config,
        code,
    };
    // 拿授权码去换 token
    const res = await axios.post(
        'https://github.com/login/oauth/access_token',
        data
    );
    // 提取 access_token
    const access_token = querystring.parse(res.data).access_token;
    const uid = String(Math.random()).substr(2, 10);
    accessTokens[uid] = access_token;
    const token = jwt.sign({ uid }, secret, { expiresIn: '2h' });
    // 响应给客户端，成功了
    ctx.type = 'html';
    ctx.body = `
        <script>
            window.localStorage.setItem('authSuccess', 'true');
            window.localStorage.setItem('token', '${token}');
            window.close();
        </script>
    `;
});

router.get('/users/current', jwtAuth({ secret }), async (ctx) => {
    // 从 ctx.state 上，拿到解析 token 后的内容
    const access_token = accessTokens[ctx.state.user.uid];
    // 向 github 拿用户的信息
    const res = await axios.get(
        'https://api.github.com/user?access_token=' + access_token
    );
    console.log(res.data);
    ctx.body = res.data;
});

app.use(KoaStatic(__dirname));
app.use(router.routes());
app.listen(3000, () => {
    console.log('Service is running at http://localhost:3000');
});
